<template>
  <div>
    <div style="padding-bottom: 1.5%">
      <el-button type="primary" :icon="Plus" @click="dialogFormVisible = true">添加</el-button><el-button type="primary"
        :icon="Delete" @click="update_title_paixu">保存</el-button>
    </div>
    <!-- 表格内容 -->
    <a-card title="专业分类" style="width: 100%">
      <el-table :data="zhuanye_data" style="width: 100%" row-key="id" border lazy
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column label="分类名称" prop="title" width="488">
          <template #default="scope">
            <el-tooltip class="box-item" effect="dark" :content="scope.row.title" placement="top">
              <el-input v-model="scope.row.title" maxlength="15" :show-overflow-tooltip="true" show-word-limit
                style="width: 55%" @blur="
                  update_title(scope.row.id, scope.row.title, scope.row.paixu)
                "></el-input>
            </el-tooltip>
            <span>（id：{{ scope.row.id }}）</span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="别名" width="300">
          <template #default="scope">
            <div>{{ pinyin.getFullChars(scope.row.title) }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="paixu" label="排序" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.paixu" @blur="update_paixu(scope.row.id, scope.row.title, scope.row.paixu)"
              style="width: 85%"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button @click="addzilei(scope.row.id)" v-if="scope.row.children">此类下添加子类</el-button>
            <el-button @click="updateClick(scope.row)" type="primary">编辑</el-button>
            <el-button type="danger" @click="delete_zhuanye(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </a-card>

    <!-- 添加专业数据对话框 -->
    <el-dialog v-model="dialogFormVisible" title="添加分类" style="width: 550px" draggable>
      <el-form :model="form" :label-position="right" :rules="rules" ref="ruleFormRef">
        <el-form-item label="所属分类" :label-width="formLabelWidth" prop="p_id">
          <el-cascader :options="options_data" :props="props1" clearable placeholder="顶级" v-model="form.p_id" />
        </el-form-item>
        <el-form-item label="名称：" :label-width="formLabelWidth" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="排序：" :label-width="formLabelWidth" prop="paixu">
          <el-input v-model="form.paixu" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex">
          <el-button type="primary" @click="onSubmit(ruleFormRef)">保存</el-button>
          <el-button @click="Addquxiao(ruleFormRef)">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加此类下的子类对话框 -->
    <el-dialog v-model="CiLeiDeZiLei" title="添加此类下的子类" draggable>
      <el-form :model="CiLeiDeZiLei_form" :label-position="right" :rules="rules" ref="CiLeiDeZiLei_ruleFormRef">
        <el-form-item label="所属分类" :label-width="formLabelWidth" prop="p_id">
          <el-cascader :options="options_data" :props="props1" clearable v-model="place_value" placeholder="顶级" />
        </el-form-item>
        <el-form-item label="名称：" :label-width="formLabelWidth" prop="title">
          <el-input v-model="CiLeiDeZiLei_form.title" />
        </el-form-item>
        <el-form-item label="排序：" :label-width="formLabelWidth" prop="paixu">
          <el-input v-model="CiLeiDeZiLei_form.paixu" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="CiLeiDeZiLei_onSubmit(CiLeiDeZiLei_ruleFormRef)">保存</el-button>
          <el-button @click="CiLeiDeZiLei_resetForm(CiLeiDeZiLei_ruleFormRef)">
            取消
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑分类 -->
    <el-dialog v-model="BianJiFenLei" title="编辑专业分类" draggable>
      <el-form :model="update_fenlei_form" :label-position="right" :rules="rules" ref="Update_fenlei_ruleFormRef">
        <el-form-item label="所属分类" :label-width="formLabelWidth" prop="p_id">
          <el-cascader :options="options_data" :props="props1" clearable placeholder="顶级"
            v-model="update_fenlei_form.id" />
        </el-form-item>
        <el-form-item label="名称：" :label-width="formLabelWidth" prop="title">
          <el-input v-model="update_fenlei_form.title" />
        </el-form-item>
        <el-form-item label="排序：" :label-width="formLabelWidth" prop="paixu">
          <el-input v-model="update_fenlei_form.paixu" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="update_fenlei_onSubmit(Update_fenlei_ruleFormRef)">保存</el-button>
          <el-button @click="update_fenlei_resetForm(Update_fenlei_ruleFormRef)">
            取消
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import axios from "axios";
import pinyin from "js-pinyin"; //汉字转化为拼音
import { onMounted, ref, reactive } from "@vue/runtime-core";
import type { FormInstance, FormRules } from "element-plus";
import { ElNotification } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";

//获取表格数据
const zhuanye_data = ref([]);
const zhuanye = async () => {
  var { data } = await axios.get("http://localhost:5200/zhuanye");
  const list: any = [];
  data.forEach((item1: any) => {
    if (item1.p_id == "") {
      list.push(item1);
      item1.children = [];
      data.forEach((item2: any) => {
        if (item2.p_id == item1.id) {
          item1.children.push(item2);
          item2.children = [];
          data.forEach((item3: any) => {
            if (item3.p_id == item2.id) {
              item2.children.push(item3);
            }
          });
          if (item2.children.length == 0) {
            delete item2["children"];
          }
        }
      });
      if (item1.children.length == 0) {
        delete item1["children"];
      }
    }
  });
  zhuanye_data.value = list;
};

//添加对话框
const dialogFormVisible: any = ref(false);
const ruleFormRef = ref<FormInstance>();
const form: any = reactive({
  p_id: "",
  title: "",
  paixu: "0",
});
//表单验证
const rules = reactive<FormRules>({
  title: [
    { required: true, message: "请输入名称", trigger: "blur" },
    // { required: true, message: "123", trigger: "blur",pattern:/^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/ },//正则
    // { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" },
  ],
});
// 添加确定
const onSubmit = async (formEl: FormInstance | undefined) => {
  // console.log(form);
  if (!formEl) return;

  await formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log(form.p_id[form.p_id.length - 1], "添加表单数据");
      let res = await axios.post("http://localhost:5200/zhuanye", {
        // ...form
        p_id: form.p_id[form.p_id.length - 1],
        title: form.title,
        paixu: form.paixu,
      });
      formEl.resetFields();
      if (res.status == 201) {
        ElNotification({
          title: "Success",
          message: `分类名称为${res.data.title}添加成功`,
          type: "success",
        });
      }
      dialogFormVisible.value = false;
      zhuanye();
    } else {
      console.log("error submit!", fields);
    }
  });
};
//添加里边取消按钮
const Addquxiao = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogFormVisible.value = false;
};
//添加获取归属分类
const props1 = {
  checkStrictly: true,
};
//获取所属分类
const options_data = ref([]);
const SuoShuFenLei = async () => {
  var { data } = await axios.get("http://localhost:5200/zhuanye");
  const newdata = data.map((item: any) => {
    return { id: item.id, p_id: item.p_id, value: item.id, label: item.title };
  });
  const list: any = [];
  newdata.forEach((item1: any) => {
    if (item1.p_id == "") {
      list.push(item1);
      item1.children = [];
      newdata.forEach((item2: any) => { });
      if (item1.children.length == 0) {
        delete item1["children"];
      }
    }
  });
  options_data.value = list;
  console.log(options_data.value, "获取所属分类");
};

//删除数据
const delete_zhuanye = async (id: any) => {
  console.log(id);
  ElMessageBox.confirm(`此操作将永久删除id为${id}数据, 是否继续?`, "提示", {
    confirmButtonText: "确定删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let res = await axios.delete(`http://localhost:5200/zhuanye/${id}`);
      if (res.status == 200) {
        ElMessage({
          type: "success",
          message: `ID为${id} 删除成功！`,
        });
        zhuanye();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: `ID为${id} 已取消删除~`,
      });
    });
};

//修改title字段
var update_titleID: any = "";
var update_titleTitle: any = "";
var update_titlePaixu: any = "";
const update_title = async (id: any, title: any, paixu: any) => {
  console.log(id, title);
  update_titleID = id;
  update_titleTitle = title;
  update_titlePaixu = paixu;
};

//修改paixu字段
const update_paixu = async (id: any, title: any, paixu: any) => {
  update_titleID = id;
  update_titleTitle = title;
  update_titlePaixu = paixu;
  console.log(paixu);
};
// 页面保存按钮
const update_title_paixu = async () => {
  if (
    (update_titleID === "" && update_titleTitle === "") ||
    update_titlePaixu === ""
  ) {
    ElMessage.error(`没有要更新的数据1`);
  } else {
    await axios.patch(`http://localhost:5200/zhuanye/${update_titleID}`, {
      title: update_titleTitle,
      paixu: update_titlePaixu,
    });
    ElMessage({
      message: `数据修改成功`,
      type: "success",
    });
    zhuanye();
  }
};

//页面此类下添加子类
const CiLeiDeZiLei: any = ref(false);
const CiLeiDeZiLei_form: any = reactive({
  p_id: "",
  title: "",
  paixu: "0",
});
const CiLeiDeZiLei_ruleFormRef = ref<FormInstance>();
const place_value = ref([]);
const addzilei = async (id: any) => {
  CiLeiDeZiLei.value = true;
  var { data } = await axios.get(`http://localhost:5200/zhuanye/${id}`);
  place_value.value = data.id;
  CiLeiDeZiLei_form.p_id = data.id;
};
// 保存按钮
const CiLeiDeZiLei_onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log(CiLeiDeZiLei_form);
      let res = await axios.post("http://localhost:5200/zhuanye", {
        ...CiLeiDeZiLei_form,
      });
      ElMessage({
        type: "success",
        message: `子类${res.data.title} 添加成功！`,
      });
      formEl.resetFields();
      CiLeiDeZiLei.value = false;
      zhuanye();
    } else {
      console.log("error submit!", fields);
    }
  });
};
//取消按钮
const CiLeiDeZiLei_resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  CiLeiDeZiLei.value = false;
};

// 编辑功能
const BianJiFenLei: any = ref(false); //编辑分类弹窗
const update_fenlei_form: any = reactive({
  id: "",
  title: "",
  paixu: "",
});
const Update_fenlei_ruleFormRef = ref<FormInstance>();
const updateClick = async (row: any) => {
  BianJiFenLei.value = true;
  const { title, paixu, id } = row;
  update_fenlei_form.title = title;
  update_fenlei_form.paixu = paixu;
  update_fenlei_form.id = id;
};
//确定按钮
const update_fenlei_onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  console.log(update_fenlei_form.id);

  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await axios.patch(
        `http://localhost:5200/zhuanye/${update_fenlei_form.id}`,
        { ...update_fenlei_form }
      );
      ElNotification({
        title: "Info",
        message: `分类名称为 ${update_fenlei_form.title} 数据修改成功`,
        type: "info",
      });
      formEl.resetFields();
      BianJiFenLei.value = false;
      zhuanye();
    } else {
      console.log("error submit!", fields);
    }
  });
};
//取消按钮
const update_fenlei_resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  BianJiFenLei.value = false;
};

onMounted(async () => {
  await zhuanye();
  await SuoShuFenLei();
});
</script>

<style lang="scss" scoped>

</style>
